package com.alipear.serverrequest;

import java.util.List;

import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.widget.Toast;

/**
 * Created by ppona_000 on 14-1-25.
 */
public class NetworkMonitor extends Service {
	NetworkStateReceiver mNetworkStateReceiver = new NetworkStateReceiver();

	@Override
    public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		IntentFilter filter = new IntentFilter();
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(mNetworkStateReceiver, filter);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mNetworkStateReceiver);

	}

	public String getTopActivityName(Context context) {
		String topActivityClassName = null;
		ActivityManager activityManager = (ActivityManager) (context
				.getSystemService(Context.ACTIVITY_SERVICE));
		List<ActivityManager.RunningTaskInfo> runningTaskInfos = activityManager
				.getRunningTasks(1);
		if (runningTaskInfos != null) {
			ComponentName f = runningTaskInfos.get(0).topActivity;
			topActivityClassName = f.getClassName();
		}
		return topActivityClassName;
	}

	public String getPackageName(Context context) {
		String packageName = context.getPackageName();
		return packageName;
	}

	public boolean isRunningForeground() {
		String packageName = getPackageName(this);
		String topActivityClassName = getTopActivityName(this);
		if (packageName != null && topActivityClassName != null
				&& topActivityClassName.startsWith(packageName)) {
			return true;
		} else {
			return false;
		}
	}

	private class NetworkStateReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			boolean success = false;
			ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
			NetworkInfo.State state = connManager.getNetworkInfo(
					ConnectivityManager.TYPE_WIFI).getState();
			if (NetworkInfo.State.CONNECTED == state) {
				success = true;
			}
			state = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
					.getState();
			if (NetworkInfo.State.CONNECTED == state) {
				success = true;
			}
			if (!success) {
				if (isRunningForeground()) {
					Toast.makeText(context, "鎮ㄧ殑缃戠粶杩炴帴宸蹭腑鏂�", Toast.LENGTH_LONG)
							.show();
					// Intent mi = new Intent();
					// mi.setClass(context, LoadingActivity.class);
					// mi.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					// startActivity(mi);
				} else {
					stopSelf();
				}

			}
		}
	}

}
